import 'package:flutter/material.dart';
import 'package:flutter_blue_plus/flutter_blue_plus.dart';
import 'mag/bluetooth_mag.dart';

class BluetoothPage extends StatefulWidget {
  const BluetoothPage({super.key});

  @override
  _BluetoothPageState createState() => _BluetoothPageState();
}

class _BluetoothPageState extends State<BluetoothPage> {
  final BluetoothManager _bluetoothManager = BluetoothManager.instance;
  bool _scanning = false;
  List<ScanResult> _scanResults = [];

  @override
  void dispose() {
    _bluetoothManager.stopScan();
    super.dispose();
  }

  //开始扫码
  Future<void> _startScan() async {
    setState(() => _scanning = true);
    await _bluetoothManager.startScan();
    setState(() {
      _scanning = false;
      _scanResults = _bluetoothManager.getScanResults();
    });
  }

  //连接
  Future<void> _connectDevice(BluetoothDevice device) async {
    try {
      await _bluetoothManager.connectDevice(device);
      // ignore: use_build_context_synchronously
      ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text("连接成功: ${device.platformName}")));
    } catch (e) {
      // ignore: use_build_context_synchronously
      ScaffoldMessenger.of(context)
          .showSnackBar(SnackBar(content: Text("连接失败: $e")));
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("蓝牙设备扫描"),
        actions: [
          IconButton(
            icon: Icon(_scanning ? Icons.stop : Icons.search),
            onPressed: _scanning ? null : _startScan,
          )
        ],
      ),
      body: ListView.builder(
        itemCount: _scanResults.length,
        itemBuilder: (context, index) {
          final result = _scanResults[index];
          return ListTile(
            title: Text(result.device.platformName.isEmpty
                ? "未知设备"
                : result.device.platformName),
            subtitle: Text(result.device.remoteId.toString()),
            trailing: ElevatedButton(
              onPressed: () => _connectDevice(result.device),
              child: const Text("连接"),
            ),
          );
        },
      ),
    );
  }
}
